package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/user")//类上面的RequestMapping可以省略
@ResponseBody //作用：返回一个非静态页面的数据
public class UserController {


    //从配置文件中读取图片保存的路径
    @Value("${img.path}")
    private String imgpath;


    @RequestMapping("/login4")
    public HashMap<String,Object> login4(String username,String password){
        HashMap<String,Object> result=new HashMap<String,Object>();
        int state=200;
        int data=1;//等于1登录成功，否则失败
       String  msg="";

        if(StringUtils.hasLength(username) && StringUtils.hasLength(password)){
            if(username.equals("admin") && password.equals("admin")){
                data=1;
                msg="";
            }else {
                msg="用户名或密码失败";
            }

        }else{ //参数为空
            msg="非法参数";
        }
        result.put("state",state);
        result.put("data",data);
        result.put("msg",msg);
        return  result;
    }


    @RequestMapping("/setsess")
    public boolean setSession(HttpServletRequest request){
        boolean result=false;
        //1.得到httpsession对象
        HttpSession session=request.getSession(true);//true表示如果没有会话，那么创建一个

        //2.使用setAtt设置值
        session.setAttribute("userinfo","userinfo");
        result=true;
        return result;
    }

    @RequestMapping("/getsess")
    public String getSession(HttpServletRequest request){
        String result=null;
        //1.得到HttpSession对象
        HttpSession session=request.getSession(false);//false 如果有会话，使用会话，如果没有不会新创建会话
        //2. getAtt得到session信息
        if(session != null && session.getAttribute("userinfo") != null) {
            result  =(String) session.getAttribute("userinfo");
        }
        return result;
    }

    @RequestMapping("/getsess2")
    public String getSession2(@SessionAttribute(value = "userinfo",required = false) String userinfo){
        return "会话"+userinfo;
    }

    @RequestMapping("/getua")
    public String getHead(HttpServletRequest request){
        return "header:"+request.getHeader("User-Agent");
    }

    @RequestMapping("/getua2")
    public String getHead2(@RequestHeader("User-Agent") String userAgent){
        return "header:"+ userAgent;
    }



    @RequestMapping("/cookie")
    public void getCookie(HttpServletRequest request){
        //得到全部的cookie
        Cookie[] cookies=request.getCookies();
        for(Cookie item:cookies) {
            log.info("Cookie Name:" + item.getName() + "| Cookie Value:"+item.getValue());
        }
    }

    @RequestMapping("/cookie2")
    public String getCookie2(@CookieValue("bbb") String cookie){
        return  "Cookie Value"+ cookie;
    }



    @RequestMapping("/sayhi")
    public  String sayHi(){
        return "你好，world" +  imgpath;
    }

    @RequestMapping(method = RequestMethod.GET, value="/sayhi2")
    public String sayHi2(){
        return "hello world";
    }

    //只支持post类型的访问方式
    @PostMapping("/sayhi3")
    public String sayHi3(){
        return "你好，world3";
    }

    @GetMapping("/sayhi4")
    public String sayHi4(){
        return "你好，world4";
    }

    @RequestMapping("/getuserbyid")
    public UserInfo getUserById(Integer id){
        // 不查数据库，伪代码，返回用户对象
        UserInfo userInfo=new UserInfo();
        userInfo.setId(id);
        userInfo.setUsername("张三");
        userInfo.setAge(18);
        return userInfo;
    }

    @RequestMapping("/login")
    public String login(String username,String password){
        return "用户名:"+username + " | 密码："+password;
    }

    @RequestMapping("/reg")
    public String reg(  UserInfo userInfo){
        return "用户信息:" + userInfo;
    }



    @RequestMapping("/login2")
    public String login2(@RequestParam("name") String username,String password){
        return "用户名:"+username + " | 密码："+password;
    }

    @RequestMapping("/login3")
    public String login3(@RequestParam(value = "name",required = false) String username,String password){
        return "用户名:"+username + " | 密码："+password;
    }

    @RequestMapping("/reg2")
    public String reg2(@RequestBody UserInfo userInfo){//如果是json格式发送的post请求，需要加上RequestBody注解
        return "用户信息:" + userInfo;
    }

    @RequestMapping("/hero/{id}/{name}")
    public String getHeroInfo(@PathVariable Integer id,@PathVariable String name){
        return "ID:"+id +"| Name:"+name;
    }



    @RequestMapping("/upimg")
    public boolean upImg(Integer uid, @RequestPart("img")MultipartFile file){
        boolean result=false;
        //1.目录=imgpath
        //2.图片名称（图片名不能重复）
        // 3。获取原上传图片的格式
       String fileName= file.getOriginalFilename();//得到原图片的名称(xxx.png)
       fileName=fileName.substring(fileName.lastIndexOf("."));//得到图片后缀
        fileName= UUID.randomUUID().toString()+fileName;


        //保存图片到本地目录
        try {
            file.transferTo(new File(imgpath+fileName));
            result=true;
        } catch (IOException e) {
            log.error("上唇啊图片失败："+e.getMessage());
        }
        return result;
    }


}
